package com.example.wan_android.viewmodel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.wan_android.http.bean.CollectionInfoData
import com.example.wan_android.http.code.CollectionRepository
import com.example.wan_android.ui.activity.WebActivity
import kotlinx.coroutines.launch

class CollectionViewModel : BaseViewModel() {
    private val _collectionLiveData = MutableLiveData<Result<List<CollectionInfoData>>>()
    val collectionLiveData = _collectionLiveData
    private var index = 0

    init {
        getCollectionList()
    }

    override fun unCollection(index: Long) {
        super.unCollection(index)
        collectionLiveData.value?.getOrNull()?.let {
            val dataList = it.filterIndexed { _, data -> data.originId != index }
            _collectionLiveData.value = Result.success(dataList)
        }
    }

    fun getCollectionList() {
        viewModelScope.launch {
            val result = CollectionRepository().fetchCollectList(index).let { result ->
                if (result.isSuccess) {
                    result.getOrNull()?.let { data ->
                        if (data.isNotEmpty()) {
                            index += 1 // 自动递增页码
                        }
                    }
                }
                _collectionLiveData.value = result
            }
        }
    }


    fun openWeb(url: String) {
        startActivity(Intent().apply {
            putExtra(WebViewModel.url, url)
        }, targetClass = WebActivity::class.java)
    }
}